﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start");
            //1.实例化连接工厂
            IConnectionFactory connFactory = new ConnectionFactory//创建连接工厂对象
            {
                HostName = "localhost",//IP地址
                Port = 5672,//端口号
                UserName = "admin",//用户账号
                Password = "admin"//用户密码
            };
            //2. 建立连接
            using (IConnection conn = connFactory.CreateConnection())
            {
                //3. 创建信道
                using (IModel channel = conn.CreateModel())
                {
                    String queueName = String.Empty;
                    if (args.Length > 0)
                        queueName = args[0];
                    else
                        queueName = "queue1";
                    //4. 申明队列 我已经通过ui界面创建了队列
                    //channel.QueueDeclare(
                    //queue: queueName,//消息队列名称
                    //durable: false,//是否缓存
                    //exclusive: false,
                    //autoDelete: false,
                    //arguments: null
                    //);
                    //5. 构造消费者实例
                    var consumer = new EventingBasicConsumer(channel);
                    //6. 绑定消息接收后的事件委托
                    consumer.Received += (model, ea) =>
                    {
                        byte[] message = ea.Body;//接收到的消息
                        Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message));

                        // 7. 发送消息确认信号（手动消息确认）
                        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                    };
                    //8.消费者开启监听
                    channel.BasicConsume(queue: "queue1", autoAck: false, consumer: consumer);


                    Console.ReadKey();
                }
            }
        }
    }
}
